package com.springboot.test.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.test.entity.NoticeEntity;
import com.springboot.test.service.MessageService;
import com.springboot.test.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务类
 */
@Component
@Slf4j
public class DelayTask {

    @Resource
    private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;

    @Resource
    private NoticeService noticeService;

    @Resource
    private MessageService messageService;

    @Scheduled(cron = "0/30 * * * * ?")
    public void taskAgainRun() {
        List<NoticeEntity> list = noticeService.list(new QueryWrapper<NoticeEntity>().lambda().eq(NoticeEntity::getSendStatus, 0).le(NoticeEntity::getSendTime, new Date()));
        for (NoticeEntity noticeEntity : list) {
            messageService.sendMessageToEveryOne(noticeEntity.getTitle(), noticeEntity.getMessage());
            noticeEntity.setSendStatus(1);
        }
        noticeService.updateBatchById(list);
    }

    public void delaySecondsTask(Runnable runnable,long delay,long time){
//        log.info(scheduledThreadPoolExecutor.toString());
        scheduledThreadPoolExecutor.scheduleAtFixedRate(runnable,delay,time, TimeUnit.SECONDS);
    }

    public void delaySecondsTask(Runnable runnable,long delay){
//        log.info(scheduledThreadPoolExecutor.toString());
        scheduledThreadPoolExecutor.schedule(runnable,delay, TimeUnit.SECONDS);
    }
}
